package server

import (
	"fmt"
	"net/http"
	"github.com/ingopansa/userinfoservice/model"
)

func (ep Endpoint)handleUserInfoEndpoint(w http.ResponseWriter, r *http.Request){
	ep.Server.logger.Debugf( "handleUserInfoEndpoint(): ep.BasePath=%s", ep.BasePath )
	ep.Server.logger.Debugf( "handleUserInfoEndpoint(): r.URL.Path=%s", r.URL.Path )

	if rawAuthBearer := r.Header.Get("Authorization"); rawAuthBearer == "" {
		renderError(ep.Server.logger, w, http.StatusUnauthorized, "no credentials provided")
	} else {
		if authBearer, err := getAuthorizationBearer(rawAuthBearer); err != nil {
			renderError(ep.Server.logger, w, http.StatusUnauthorized, "invalid credentials")
		} else {
			if accessTokenData, err := ep.TokenProvider.Introspect(authBearer); err != nil {
				renderError(ep.Server.logger, w, http.StatusUnauthorized, "access_token is invalid")
			} else {
				if !accessTokenData.Active {
					ep.Server.logger.Debugf( "access_token is not valid" )
					renderError(ep.Server.logger, w,http.StatusUnauthorized, "access_token is not valid")
				} else if accessTokenData.Sub == " " {
					ep.Server.logger.Debugf( "access_token is valid, but no user returned")
					renderError(ep.Server.logger, w,http.StatusNotFound, "user not found")
				} else {
					ep.Server.logger.Debugf( "access_token is valid and sub resolved to: %s", accessTokenData.Sub)
					if user, err := ep.Server.storage.GetUser(accessTokenData.Sub); err != nil {
						renderError(ep.Server.logger, w,http.StatusNotFound, fmt.Sprintf("error: %v", err))
					} else {
						ep.Server.logger.Debugf( "user.Groups: %v", user.Groups )
						var groups = []string{}
						for _, group := range user.Groups{
							ep.Server.logger.Debugf( "added %s\n", group.Group )
							groups = append(groups, group.Group)
						}

						userInfo := model.UserInfo{
							Subject: 		accessTokenData.Sub,
							Name: 			user.Name,
							GivenName: 		user.GivenName,
							FamilyName:	 	user.FamilyName,
							Email:			user.Email,
							EmailVerified:	user.EmailVerified,
							PhoneNumber:	user.PhoneNumber,
							Groups:			groups,
						}

						renderResult(ep.Server.logger, w, r, userInfo)
					}
				}
			}
		}
	}
}

